package com.wangzeqi.changliaoba.worldlet.circle;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.toolbox.NetworkImageView;
import com.easemob.chat.EMChatManager;
import com.wangzeqi.BmobEntity.FriendCircleComment;
import com.wangzeqi.BmobEntity.FriendCircleText;
import com.wangzeqi.changliaoba.R;

import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;

import static com.wangzeqi.changliaoba.R.id.comment_item;

/**
 * Created by dllo on 16/3/7.
 */
public class FriendCircleAdapter extends BaseAdapter {
    private int p = 0;
    private Context context;
    private List<FriendCircleText> datas;
    private CommentAdapter commentAdapter;

    public void addData(List<FriendCircleText> datas) {
        this.datas = datas;
        notifyDataSetChanged();
    }

    public FriendCircleAdapter(Context context) {
        this.context = context;
        commentAdapter = new CommentAdapter(context);

    }

    @Override
    public int getCount() {

        return datas == null ? 0 : datas.size();
    }

    @Override
    public Object getItem(int position) {

        return datas.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View view, final ViewGroup parent) {
        TextViewHolder holder;
        holder = new TextViewHolder();

        if (view == null) {
            view = LayoutInflater.from(context).inflate(R.layout.friend_circle_text_item, null);
            holder.userPhoto = (NetworkImageView) view.findViewById(R.id.friend_circle_user_picture);
            holder.userName = (TextView) view.findViewById(R.id.friend_circle_user_name_up);
            holder.text = (TextView) view.findViewById(R.id.friend_circle_user_text);
            holder.likeCount = (TextView) view.findViewById(R.id.zan_all);
            holder.btnPin = (ImageButton) view.findViewById(R.id.friend_circle_text_pl);
            holder.btnPinGreen = (ImageButton) view.findViewById(R.id.friend_circle_text_pl_green);
            holder.btnZanGreen = (ImageButton) view.findViewById(R.id.friend_circle_text_zan);
            holder.btnZanRed = (ImageButton) view.findViewById(R.id.friend_circle_text_zan_red);
            holder.textTime = (TextView) view.findViewById(R.id.friend_circle_time);
            holder.listView = (ListView) view.findViewById(R.id.friend_circle_pl_lv);
            addHeadView(holder.listView, position);

            view.setTag(holder);
        } else {
            holder = (TextViewHolder) view.getTag();

        }
        if (datas != null && datas.size() > 0) {


            holder.userName.setText(datas.get(position).getUsername());
            holder.text.setText(datas.get(position).getText());
            holder.likeCount.setText(datas.get(position).getLike_count().toString());
            holder.textTime.setText(datas.get(position).getCreatedAt());
            final TextViewHolder finalHolder = holder;
            holder.btnZanGreen.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    finalHolder.btnZanGreen.setVisibility(View.INVISIBLE);
                    finalHolder.btnZanRed.setVisibility(View.VISIBLE);
                    FriendCircleText friendCircle = new FriendCircleText();
                    friendCircle.increment("like_count", 1); // 分数递增1
                    friendCircle.update(context, datas.get(position).getObjectId(), new UpdateListener() {
                        @Override
                        public void onSuccess() {
                            notifyDataSetChanged();
                        }

                        @Override
                        public void onFailure(int i, String s) {
                            finalHolder.btnZanGreen.setVisibility(View.VISIBLE);
                            finalHolder.btnZanRed.setVisibility(View.INVISIBLE);
                            Log.d("FriendCircleAdapter", "失败－－－－>>>" + s);
                        }
                    });
                }
            });
            holder.btnZanRed.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    finalHolder.btnZanGreen.setVisibility(View.VISIBLE);
                    finalHolder.btnZanRed.setVisibility(View.INVISIBLE);
                    FriendCircleText friendCircle = new FriendCircleText();

                    friendCircle.increment("like_count", -1); // 分数递减1
                    friendCircle.update(context, datas.get(position).getObjectId(), new UpdateListener() {
                        @Override
                        public void onSuccess() {
                            notifyDataSetChanged();
                        }

                        @Override
                        public void onFailure(int i, String s) {
                            finalHolder.btnZanGreen.setVisibility(View.INVISIBLE);
                            finalHolder.btnZanRed.setVisibility(View.VISIBLE);
                            Log.d("FriendCircleAdapter", "请求失败－－－－>>>" + s);
                        }
                    });
                }
            });
            holder.btnPin.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    finalHolder.btnPinGreen.setVisibility(View.VISIBLE);
                    finalHolder.btnPin.setVisibility(View.INVISIBLE);
                    finalHolder.listView.setVisibility(View.GONE);

                }
            });
            holder.btnPinGreen.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    finalHolder.btnPinGreen.setVisibility(View.INVISIBLE);
                    finalHolder.btnPin.setVisibility(View.VISIBLE);

                    finalHolder.listView.setVisibility(View.VISIBLE);
                    if (p != 0) {
                        parent.getChildAt(p).findViewById(R.id.friend_circle_pl_lv).setVisibility(View.GONE);
                        parent.getChildAt(p).findViewById(R.id.friend_circle_text_pl).setVisibility(View.INVISIBLE);
                        parent.getChildAt(p).findViewById(R.id.friend_circle_text_pl_green).setVisibility(View.VISIBLE);
                    }
                    p = position;
                    BmobQuery<FriendCircleComment> comment = new BmobQuery<>();
                    comment.addWhereEqualTo("text_user", datas.get(position).getUsername());  //名字等于该位置发说说的用户名
                    comment.addWhereEqualTo("text_id", datas.get(position).getObjectId());    //条件：id等于该位置发说说的用户id
                    comment.findObjects(context, new FindListener<FriendCircleComment>() {
                        @Override
                        public void onSuccess(List<FriendCircleComment> list) {
                            commentAdapter.addComment(list);
                            finalHolder.listView.setAdapter(commentAdapter);

                        }

                        @Override
                        public void onError(int i, String s) {
                            Toast.makeText(context, "评论获取失败", Toast.LENGTH_SHORT).show();
                        }
                    });


                }
            });

        }
        return view;
    }

    private class TextViewHolder {

        private NetworkImageView userPhoto;
        private TextView userName, text, likeCount, textTime;
        private ImageButton btnZanRed, btnZanGreen, btnPinGreen, btnPin;
        private ListView listView;

    }

    private void addHeadView(ListView listView, final int pos) {
        LinearLayout heardView = (LinearLayout) LayoutInflater.from(context).inflate(R.layout.friend_circle_pinglun_henad_layout, null);
        final EditText edt;
        Button sendBtn;
        edt = (EditText) heardView.findViewById(R.id.ping_lun);
        sendBtn = (Button) heardView.findViewById(R.id.ping_lun_btn);

        sendBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (edt.getText().toString().trim().length() > 0) {
                    saveBmobComment(edt.getText().toString(), pos);
                    Toast.makeText(context, "评论成功", Toast.LENGTH_SHORT).show();
                    edt.setText("");
                    //TODO edt里面字要是很多的字会看不见发送按钮

                } else {
                    Toast.makeText(context, "评论内容不能为空", Toast.LENGTH_SHORT).show();
                }
            }
        });
        listView.addHeaderView(heardView);
    }

    private void saveBmobComment(final String comment, int pos) {
        FriendCircleComment obj = new FriendCircleComment();
        obj.setDoen_username(EMChatManager.getInstance().getCurrentUser());
        obj.setDown_text(comment);
        obj.setText_id(datas.get(pos).getObjectId());
        obj.setText_user(datas.get(pos).getUsername());
        obj.setDown_like_count(0);
        obj.save(context, new SaveListener() {
            @Override
            public void onSuccess() {

            }

            @Override
            public void onFailure(int i, String s) {
                Toast.makeText(context, "保存失败" + s, Toast.LENGTH_SHORT).show();
            }
        });
    }

    class CommentAdapter extends BaseAdapter {
        List<FriendCircleComment> commentData;
        Context context;

        public void addComment(List<FriendCircleComment> commentData) {
            this.commentData = commentData;
            notifyDataSetChanged();
        }

        public CommentAdapter(Context context) {
            this.context = context;

        }

        @Override
        public int getCount() {
            return commentData == null ? 0 : commentData.size();
        }

        @Override
        public Object getItem(int position) {
            return commentData == null ? 0 : commentData.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            DownViewHolder dvh;
            dvh = new DownViewHolder();
            if (convertView == null) {
                convertView = LayoutInflater.from(context).inflate(R.layout.friend_circle_pinglun_list_item, null);
                dvh.tvComment = (TextView) convertView.findViewById(R.id.friend_circle_comment_user_text);
                dvh.tvUserName = (TextView) convertView.findViewById(R.id.friend_circle_comment_user_name);
                dvh.tvLikeCount = (TextView) convertView.findViewById(R.id.zan_comment);
                dvh.imGreen = (ImageButton) convertView.findViewById(R.id.friend_circle_comment_green);
                dvh.imRed = (ImageButton) convertView.findViewById(R.id.friend_circle_comment_red);
                dvh.linearLayout = (LinearLayout) convertView.findViewById(comment_item);
                convertView.setTag(dvh);
            } else {
                dvh = (DownViewHolder) convertView.getTag();
            }
            if (commentData != null && commentData.size() > 0) {
                dvh.tvComment.setText(commentData.get(position).getDown_text());
                dvh.tvUserName.setText(commentData.get(position).getDoen_username());
//                dvh.tvLikeCount.setText(commentData.get(position).getDown_like_count());
                final DownViewHolder finalDvh = dvh;
                dvh.imGreen.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        finalDvh.imGreen.setVisibility(View.INVISIBLE);
                        finalDvh.imRed.setVisibility(View.VISIBLE);
                    }
                });

                dvh.imRed.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        finalDvh.imRed.setVisibility(View.INVISIBLE);
                        finalDvh.imGreen.setVisibility(View.VISIBLE);
                    }
                });


                dvh.linearLayout.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        showDiaLog();
                    }
                });
            }

            return convertView;
        }

        private void showDiaLog() {
            View view = LayoutInflater.from(context).inflate(R.layout.comment_goback_layout,null);
            final EditText editText;
            editText = (EditText) view.findViewById(R.id.comment_goback_et);
            AlertDialog.Builder dialog = new AlertDialog.Builder(context);
            dialog.setTitle("回复评论");
            dialog.setView(view);
            dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    commentCallBack();
                }
            });
            dialog.setNegativeButton("取消", null);
            dialog.show();
        }

        private void commentCallBack() {
            

        }

        private class DownViewHolder {

            TextView tvUserName, tvComment, tvLikeCount;
            ImageButton imGreen, imRed;
            LinearLayout linearLayout;
        }
    }
}
